﻿using Microsoft.EntityFrameworkCore;
using WMS.FC.Domain.PersistenceObject.System;
using WMS.FC.Domain.Repository;
using WMS.FC.Infrastructure.Common;

namespace WMS.FC.Infrastructure.Repository
{
    public class UserRepository : RepositoryBase, IUserRepository
    {
        public UserRepository(WmsDbContext dbContext) : base(dbContext)
        {
        }

        public async Task<UserPO?> GetUserByAccount(string userAccount)
        {
            var entities = dbContext.Set<UserPO>();
            return await entities.AsNoTrackingWithIdentityResolution().Where((entity) => entity.Account == userAccount).FirstOrDefaultAsync();
        }

        public async Task<int> AddLoginError(UserPO userPO)
        {
            var entities = dbContext.Set<UserPO>();
            userPO.LoginErrorCount++;
            if (userPO.LoginErrorCount > 6)
                userPO.IsLocked = true;
            entities.Update(userPO);
            return await dbContext.SaveChangesAsync();
        }

        public async Task<int> ResetLoginFail(UserPO userPO)
        {
            var entities = dbContext.Set<UserPO>();
            userPO.LoginErrorCount = 0;
            userPO.IsLocked = false;
            entities.Update(userPO);
            return await dbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userPO"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> ChangePassword(UserPO userPO)
        {
            var entities = dbContext.Set<UserPO>();
            entities.Update(userPO);
            return await dbContext.SaveChangesAsync();
        }
    }
}
